import { LayaAPIAction, LayaAPICode, LayaAPIStatus } from "../AIConfig";
import { AICore } from "../AICore";
import { AIPanel } from "../AIPanel";
import { reclog, reportQueryError, trimBR, trimComment } from "../AIUtils";
import { IDEAgent } from "../IDEAgent";
import { SkyBoxGenData } from "../Imagen";
import { LayaAPI } from "../LayaAPI";
import { 服务过期, 点数不够 } from "../StoreServer";
import { Thinkingdata } from "../Thinkingdata";
import { CustomButtonsField } from "../field/CustomButtonsField";
import { FileField } from "../field/FileField";
import { TextAreaField } from "../field/TextAreaField";
import { TipField } from "../field/TipField";
import { AITask } from "./AITask";


export class AITaskGenSkyImg extends AITask{
    private imageName = 'skyimg'+Date.now()+'.png';
    static EditObjName = '生成全景图'

    _data: SkyBoxGenData = IEditor.DataWatcher.watch(new SkyBoxGenData());
    private genData:any;
    //正在下载文件。由于文件比较大，所以需要这个
    private _downloadingResult=false;

    private async  onOKClick(e:Event){
        let asset = await this.genImage();
        Editor.scene?.setSelection([asset], "asset");
        await Editor.assetDb.getAsset(this.imageName);
        this.genAsset=asset;
    }
    
    async showUI(){
        let me = this;
        let msg:any = {
            name: "生成天空盒",
            properties: [
                {
                    label:'描述:',
                    name: "prompt",
                    type: "string",
                    default:this._data.prompt,
                    inspector: TextAreaField,
                    onChange: (key: string, val: any, data: any) => {
                        this._data.prompt = val;
                    }
                },
                {
                    label:'类型:',
                    name: "template",
                    type: 'string',
                    default:this._data.template,
                    enumSource: [{ name: "室内", value: "0" }, { name: "室外", value: "1" }],
                    onChange: (key: string, val: string, data: any) => {
                        this._data.template=val;
                    }
                },
                {
                    name: "CustomButton",
                    inspector: CustomButtonsField,
                    onClick:(e:gui.Event)=>{
                        me.onOKClick(null);
                    }
                },
            ]
        }
        this.msgid = await AIPanel.ins.addMsg(msg,-1,{data:this._data})        
    }

    async getImageUrl():Promise<string>{
        let data = this._data;
        let wmsg = await AIPanel.ins.startWaitMsg('生成中(天空盒生成时间较长,预计超过1分钟，请耐心等待)');
        let st = Date.now();
        //埋点： generateskybox 开始
        Thinkingdata.ins.track("genSkyboxStart", {prompt:data.prompt});
        const genData: any = this.genData = await LayaAPI.create().laya_text2SkyBox(data);
        let dt = (Date.now()-st)/1000;
        Thinkingdata.ins.track("genSkyboxEnd", {duration:dt});
        //埋点： generateskybox 结束
        console.log('gen sky image:',dt)
        // const genData: any = await LayaAPI.create().laya_text2img({
        //     prompt:data.prompt,
        //     trans:true
        // });
        AIPanel.ins.removeMsg(wmsg);
        if(genData.code != LayaAPICode.CodeSuccess){
            this.cancel();
            this.setui("天空盒图片生成失败！");
            return null;
        }

        if(genData.data.status == LayaAPIStatus.TaskStatusNeedUsageCount){
            if( await 点数不够(LayaAPIAction.generate_skybox)){
                return await this.getImageUrl()
            }
        }
        if( genData.data.status==LayaAPIStatus.TaskStatusSubscriptionExpired){
            if( await 服务过期(LayaAPIAction.generate_skybox)){
                return await this.getImageUrl();
            }
        }        

        if(genData.data.status == LayaAPIStatus.TaskStatusDone){
            return genData.data.url;
        }
        reportQueryError(genData.data.status);        
        return null;
    }

    /**
     * 生成天空盒贴图。结果是一个asset
     */
    async genImage(){
        let data = this._data;
        this.imageName = 'env_'+Date.now()+'.png';

        //提示生成图片中
        let url = await this.getImageUrl();

        if(url){
            let buffer: any;
            // 通过fetch下载图片文件,得到图片中的数据、
            let response: Response = await fetch(LayaAPI.formatImageUrl(url));
            // let response: Response = await fetch(LayaAPI.formatImageUrl(genData.data.images[0]));
            if(response.ok){
                const buff = await response.arrayBuffer();
                buffer = Buffer.from(buff);
            }

            let skyimgTmp = await IDEAgent.inst.saveBuffToTmp(buffer,'png');
            let asset: any = await IDEAgent.inst.crateAIAssetFromFile(skyimgTmp, 'skybox',this.imageName);
            //保存ai信息
            IDEAgent.inst.setAIInfo(asset.id,data,true);
            this.genAsset=asset;

            // let l = new gui.Loader();
            // l.src=skyimgTmp;
            // l.width=200;
            // l.height=200;
            // AIPanel.ins.addMsg(l)
            AIPanel.ins.addMsg( `<img src="${skyimgTmp}" width=${200} height=${100} />`,-1);
            return asset;
        }
        console.log('出错了')
        return null;
    }

    private execend=false;
    async execute(): Promise<void> {
        this.imageName = 'env_'+Date.now()+'.png';
        let oldasset = await Editor.assetDb.getAsset(this.imageName);
        if(oldasset){
            let ret = await Editor.showMessageBox({
                message: '已经存在资源:'+this.imageName+',是否覆盖?',
                buttons: ['是', '否'],
                defaultId: 0
            });
            if (0 == ret.response) {
                //TODO
            }else{
                this.cancel();
                this.setui("取消生成");
                return;
            }
        }

        this.execend=false;
        let data = this._data;
        this.showUI();
        let b = await this.waitIt();

        this.execend=true;
        AICore.inst.say('天空盒图片生成完成');
        if(data.depth != '0'){
            let url: string = this.genData.data.url;
            const pi: number = url.lastIndexOf('.');
            const sub: string = url.substring(pi+1,url.length);
            url = url.substring(0,pi);
            url = LayaAPI.formatImageUrl(`${url}_d.${sub}`);

            AIPanel.ins.addMsg(`<a href=${url} download> 点击下载深度图 </a>`,-1);
        }
    }
}
